package com.tianji.jersey.resource;

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class XmlMarshaller<T> {
	private Log log = LogFactory.getLog(XmlMarshaller.class);
	private String contextPath;
	private T object;

	public XmlMarshaller(String contextPath, T object){
		this.contextPath = contextPath;
		this.object = object;
	}

	public XmlMarshaller(T object){
		this.contextPath = object.getClass().getPackage().getName();
		this.object = object;
	}

	public String marshal() {
		if (object == null) {
			return null;
		}

		try {
			JAXBContext context = JAXBContext.newInstance(contextPath);
			Marshaller marshaller = context.createMarshaller();
			StringWriter sw = new StringWriter();
			marshaller.marshal(object, sw);
			sw.close();
			return sw.toString();
		} catch (JAXBException e) {
			if (log.isErrorEnabled()) {
				log.error("JAXBException, " + e);
			}
		} catch (IOException e) {
			if (log.isErrorEnabled()) {
				log.error("IOException, " + e);
			}
		}
		return null;
	}
}
